package com.hsmw.api.controller.pm;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hsmw.api.config.jwt.CurrentHsmwUserUtils;
import com.hsmw.api.mapper.HsmwForcemanItemMapper;
import com.hsmw.api.service.*;
import com.hsmw.api.utils.GaoDeInfoUtils;
import com.hsmw.api.vo.*;
import com.hsmw.common.base.BaseController;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.*;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import com.hsmw.domain.form.GetObjectByIdForm;
import com.hsmw.domain.vo.*;
import com.hsmw.domain.vo.DriverCountVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;

@Api(tags = "项目经理端相关接口表")
@RestController
@RequestMapping(value = "/api/pm")
public class HsmwPMController extends BaseController<HsmwUserService, HsmwUser> {



    @Autowired
    private CurrentHsmwUserUtils currentHsmwUserUtils;

    @Autowired
    private HsmwItemService hsmwItemService;

    @Autowired
    private HsmwOrderService  hsmwOrderService;

    @Autowired
    private HsmwOrderForceManRelationService hsmwOrderForceManRelationService;

    @Autowired
    private HsmwOrderVehicleRelationService hsmwOrderVehicleRelationService;

    @Autowired
    private HsmwOrderVehicleRequestService hsmwOrderVehicleRequestService;


    @Autowired
    private HsmwDictDataService hsmwDictDataService;



    @Autowired
    private GaoDeInfoUtils gaoDeInfoUtils;


    @Autowired
    private HsmwAuditService hsmwAuditService;





    @Autowired
    private HsmwPmUserService hsmwPmUserService;




    @Autowired
    private HsmwHtnUserService hsmwHtnUserService;




    @Autowired
    private HsmwForcemanItemMapper hsmwForcemanItemMapper;

    /**
     * 项目信息新增
     *
     * @param
     * @return
     */
    @ApiOperation(value = "项目信息新增 项目新增后，默认审核状态是 审核中", notes = "项目信息新增", produces = "application/json")
    @PostMapping("/saveOrUpdateHsmwItemInfo")
    public DataResponse addItemInfo(@RequestBody  HsmwItem  hsmwItem) {
        try {
            HsmwPmUser currentUser = currentHsmwUserUtils.getCurrentPmUserInfo();
            if(UserTypeEnum.FOREMAN.getValue().equals(currentUser.getType()) ){
                return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您已经是工长的身份，不能再申请项目！");
            }
            if(UserTypeEnum.VISITOR.getValue().equals(currentUser.getType()) && AuditStatusEnum.UNRECEIVED.getValue().equals(currentUser.getAuditStatus())){
                return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您正在申请工长的身份，不能再申请项目！");
            }
            List<HsmwAudit> audits =hsmwAuditService.list(new LambdaQueryWrapper<HsmwAudit>()
                    .eq(HsmwAudit::getUserId,currentUser.getId()));
            if(StringUtils.isListNotNull(audits)){
                return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您正在认证司机身份，不能再申请项目！");
            }
            if(StringUtils.isBlank(hsmwItem.getId())){
                List<HsmwItem> items = hsmwItemService.list(new LambdaQueryWrapper<HsmwItem>()
                        .eq(HsmwItem::getName,hsmwItem.getName()));
                if(CollectionUtil.isNotEmpty(items)){
                    return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您输入的项目名称已存在，请重新输入！");
                }
            }
            String  identifyNum= hsmwItemService.saveOrUpdateHsmwItemInfo(hsmwItem);
            HashMap result = new HashMap();
            result.put("itemIdentifyNum",identifyNum);
            return new DataResponse(result);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"项目信息新增失败，请联系管理员！");
        }
    }

    /**
     * 分页
     *
     * @param
     * @return
     */
    @ApiOperation(value = "获取项目列表", notes = "获取项目分页列表  ", produces = "application/json")
    @PostMapping("/getHsmwItemList")
    public DataResponse getHsmwItemPage() {
        HsmwPmUser hsmwUser = currentHsmwUserUtils.getCurrentPmUserInfo();
        List<HsmwItem> data = hsmwItemService.list(new LambdaQueryWrapper<HsmwItem>().
                eq(HsmwItem::getCreateUser,hsmwUser.getId()));
        data.stream().forEach(hsmwItem -> {
            if(null!=hsmwItem.getAuditSuccessTime()){
                Duration duration = java.time.Duration.between(hsmwItem.getAuditSuccessTime(),  LocalDateTime.now() );
                long days = duration.toDays();
                hsmwItem.setContinusDays(days);
            }else {
                hsmwItem.setContinusDays(0L);
            }
        });

        return new DataResponse(data);
    }


    /**
     * 更改当前项目
     *
     * @param
     * @return
     */
    @ApiOperation(value = "更改当前项目 id 必输", notes = "更改当前项目", produces = "application/json")
    @PostMapping("/updateCurrentItem")
    public DataResponse updateCurrentItem(@RequestBody  HsmwItem  hsmwItem) {
        try {
            HsmwPmUser hsmwUser = currentHsmwUserUtils.getCurrentPmUserInfo();
            HsmwItem param = new HsmwItem();
            param.setIsCurrent(CommonConstants.NO);
            hsmwItemService.update(param,new LambdaQueryWrapper<HsmwItem>().eq(HsmwItem::getCreateUser,hsmwUser.getId()));
            hsmwItem.setIsCurrent(CommonConstants.YES);
            hsmwItemService.updateById(hsmwItem);
            return new DataResponse();
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"更改当前项目失败，请联系管理员！");
        }
    }

    /**
     * 新增或者修改工长信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "删除项目下面的工长信息", notes = "删除项目下面的工长信息  ", produces = "application/json")
    @PostMapping("/moveForemanInfo")
    public DataResponse moveForemanInfo(@RequestBody  HsmwPmUser  hsmwUser) {
        //移除工长之前 首先判断工长是否有进行中的订单
        HashMap param = new HashMap();
        param.put("userId",hsmwUser.getId());
        List<PMGoingOrderVO> orderList = hsmwOrderService.selectGOingOrderListByParam(param);
        if(CollectionUtil.isNotEmpty(orderList)){
            return  new DataResponse(CommonConstants.ResponseStatus.HAS_ORDER,"您所要删除的工长有进行中的订单，不能删除！");
        }
        HashMap params = new HashMap();
        params.put("userId",hsmwUser.getId());
        hsmwHtnUserService.removeItemInfoById(param);
        return new DataResponse();
    }

    /**
     * 完成项目信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "完成项目信息", notes = "完成项目信息  ", produces = "application/json")
    @PostMapping("/complateItemInfo")
    public DataResponse complateItemInfo(@RequestBody  HsmwItem  hsmwItem) {
        HsmwPmUser currentUser = currentHsmwUserUtils.getCurrentPmUserInfo();
        HashMap param = new HashMap();
        param.put("itemId",hsmwItem.getId());
        List<PMGoingOrderVO> orderList = hsmwOrderService.selectGOingOrderListByParam(param);
        if(CollectionUtil.isNotEmpty(orderList)){
            return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"您所要完成的项目有进行中的订单，不能完成！");
        }

        HashMap params = new HashMap();
        params.put("itemId",hsmwItem.getId());
        hsmwPmUserService.removeItemInfoByItemId(params);
        //将项目状态变为完成
        hsmwItem.setItemStatus("1");
        hsmwItem.setIsCurrent(CommonConstants.NO);
        hsmwItemService.updateById(hsmwItem);
        //查询其他的未完成的项目信息 并随机将其中一个变为当前项目
        List<HsmwItem> items =  hsmwItemService.list(new LambdaQueryWrapper<HsmwItem>()
                .eq(HsmwItem::getCreateUser,currentUser.getId())
                .eq(HsmwItem::getItemStatus,CommonConstants.NO)
                .ne(HsmwItem::getId,hsmwItem.getId()));
        if(CollectionUtil.isNotEmpty(items) && items.size()>0){
            HsmwItem item = items.get(0);
            item.setIsCurrent(CommonConstants.YES);
            hsmwItemService.updateById(item);
        }
        return new DataResponse();
    }



    /**
     * 分页
     *
     * @param
     * @return
     */
    @ApiOperation(value = "获取项目下面的工长列表", notes = "获取项目下面的工长列表  ", produces = "application/json")
    @PostMapping("/getForeManListByItemInfo")
    public DataResponse getForeManListByItemInfo() {
        List<HashMap> result = new ArrayList<>();
        HsmwPmUser hsmwUser = currentHsmwUserUtils.getCurrentPmUserInfo();
        List<HsmwItem> items =  hsmwItemService.list(new LambdaQueryWrapper<HsmwItem>()
                .eq(HsmwItem::getCreateUser,hsmwUser.getId()));
        items.stream().forEach(hsmwItem -> {
            HashMap param = new HashMap();
            param.put("itemId",hsmwItem.getId());
            List<HsmwHtnUser> data = hsmwForcemanItemMapper.selectForemanListByItemId(param);
            HashMap map = new HashMap();
            map.put("itemInfo",hsmwItem);
            map.put("foremanList",data);
            result.add(map);
        });
        return new DataResponse(result);
    }

    ///下面项目的 查询首页的信息 begin


    /**
     * 根据ID查询数据
     *
     * @param form
     * @return
     */
    @ApiOperation(value = "获取项目详情 总方量和工长数量+持续时间", notes = "获取项目详情", produces = "application/json")
    @PostMapping("/getHsmwAuditById")
    public DataResponse getHsmwItemById(@RequestBody GetObjectByIdForm form) {
        HsmwItem hsmwItem = hsmwItemService.getHsmwItemById(form.getKey());
        List<HsmwHtnUser> forceManList = hsmwHtnUserService.list(Wrappers.lambdaQuery(HsmwHtnUser.class)
                .eq(HsmwHtnUser::getItemId, hsmwItem.getId())
                .eq(HsmwHtnUser::getType, CommonConstants.UserRole.FOREMAN.name())
                .eq(HsmwHtnUser::getEnabled,true));
        if(null!=hsmwItem.getAuditSuccessTime()){
            Duration duration = java.time.Duration.between(hsmwItem.getAuditSuccessTime(),  LocalDateTime.now() );
            long days = duration.toDays();
            hsmwItem.setContinusDays(days);
        }else {
            hsmwItem.setContinusDays(0L);
        }
        HashMap params = new HashMap();
        params.put("itemId",form.getKey());
        Double  res = hsmwOrderService.selectItemInfoByItemId(params);
        if(StringUtils.isNotNull(res)){
            hsmwItem.setVolumeSum(res);
        }else {
            hsmwItem.setVolumeSum(0.00);
        }
        hsmwItem.setForcemanCount(forceManList.size());
        HashMap param = new HashMap();
        param.put("itemId",form.getKey());
        List<ForemanCountVO> foremanCountVOS = hsmwOrderService.getFormanCountInfo(param);
        hsmwItem.setForceManCountList(foremanCountVOS);
        return new DataResponse(hsmwItem);
    }

    /**
     * 查询进行中的订单进度信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "项目经理端：查询指定的项目 进行中的订单进度信息 ", notes = "查询进行中的订单进度信息", produces = "application/json")
    @PostMapping("/getGoingOrderInfo")
    public DataResponse getGoingOrderInfo(@RequestBody GetObjectByIdForm form) {
        try {
            //获取工长所在项目的项目名称和项目id。
            HashMap result = new HashMap();
            HashMap param = new HashMap();
            param.put("itemId",form.getKey());

            List<PMGoingOrderVO> resultList = new ArrayList<>();
            List<PMGoingOrderVO> orderList = hsmwOrderService.selectGOingOrderListByParam(param);
            orderList.stream().forEach(pmGoingOrderVO -> {
                int minites = Integer.parseInt(StringUtils.isBlank(pmGoingOrderVO.getStartWorkTime())? "0":pmGoingOrderVO.getStartWorkTime());
                int day = minites/1440;
                int hour= (minites)/60;
                int minite = (minites%1440)%60;
                double hours  = (double)(minites/60);
                pmGoingOrderVO.setStartWorkTime(hour+"小时");
                double  speed=0.0;
                if(0!= hours){
                    speed= Integer.parseInt(StringUtils.isBlank(pmGoingOrderVO.getRealTimeVolume())?"0":pmGoingOrderVO.getRealTimeVolume())/hours;
                }
                System.out.println("speed==="+speed);
                String goingStatus =(speed <=20? "较慢":"较快");
                pmGoingOrderVO.setGoingStatus(goingStatus);
                resultList.add(pmGoingOrderVO);
            });
            result.put("orderList",resultList);
            //查询 方量统计
            return new DataResponse(result);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"查询进行中的订单进度信息，请联系管理员！");
        }
    }




    /**
     * 查询进行中的订单进度信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "项目经理端：工长方量统计信息 ", notes = "工长方量统计信息", produces = "application/json")
    @PostMapping("/getFormanCountInfo")
    public DataResponse getFormanCountInfo(@RequestBody  HsmwItem  hsmwItem) {
        try {
            HashMap param = new HashMap();
            param.put("itemId",hsmwItem.getId());
            List<ForemanCountVO> orderList = hsmwOrderService.getFormanCountInfo(param);
            //查询 方量统计
            return new DataResponse(orderList);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"查询进行中的订单进度信息，请联系管理员！");
        }
    }



    /**
     * 混凝土标号统计
     *
     * @param
     * @return
     */
    @ApiOperation(value = "项目经理端：混凝土标号统计 staticsType=default 首页的近七天的数据 ；staticsType=day 按天的统计；staticsType=week 按周统计；staticsType=month统计", notes = "混凝土标号统计", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "staticsType",value = " staticsType=default 首页的近七天的数据 ；staticsType=day 按天的统计；staticsType=month 月统计"),
            @ApiImplicitParam(name = "itemId",value = "项目ID")
    })
    @PostMapping("/concreteCountInfo")
    public DataResponse concreteCountInfo(String staticsType,String itemId) {
        if(StringUtils.isBlank(staticsType) ){
            return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"查询的视图类型不能为空，请重新输入！");
        }
        if(StringUtils.isBlank(itemId) ){
            return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"查询的项目id不能为空，请重新输入！");
        }
        try {
            HsmwPmUser hsmwUser = currentHsmwUserUtils.getCurrentPmUserInfo();
            HashMap param = new HashMap();
            param.put("userId",hsmwUser.getId());
            param.put("itemId",itemId);
            HashMap orderList = hsmwOrderService.concreteCountInfo(staticsType,param);
            //查询 方量统计
            return new DataResponse(orderList);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"混凝土标号统计异常，请联系管理员！");
        }
    }
    ///下面项目的 查询首页的信息 end




    /**
     * 查询项目经理端的订单列表的信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "项目经理的订单管理", notes = "项目经理的订单管理", produces = "application/json")
    @PostMapping("/getOrderStatistics")
    public DataResponse getOrderInfoByStatus(@RequestBody OrderQUeryVO orderQUeryVO) {
        try {
            HsmwPmUser hsmwUser = currentHsmwUserUtils.getCurrentPmUserInfo();
            //获取工长所在项目的项目名称和项目id。
            HashMap result = new HashMap();
            HashMap param = new HashMap();
            param.put("orderStatus",OrderStatusEnum.COMPLETED.getValue());
            param.put("userId",hsmwUser.getId());
            if(StringUtils.isNotBlank(orderQUeryVO.getKeyWords())){
                param.put("keyWords",orderQUeryVO.getKeyWords());
            }
            List<PMOrderCountVO> orderList = hsmwOrderService.selectOrderListByParam(param);
            result.put("orderList",orderList);
            //查询 方量统计
            return new DataResponse(result);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"获取订单列表失败，请联系管理员！");
        }
    }


    /**
     * 查询项目经理 端的订单列表的信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "查询订单司机信息", notes = "查询订单的子订单信息", produces = "application/json")
    @PostMapping("/getChildOrderStatistics")
    public DataResponse getChildOrderStatistics(@RequestBody OrderQueryParam orderQueryParam) {
        try {
            HashMap param = new HashMap();
            param.put("orderId",orderQueryParam.getOrderId());
            List<DriverCountVO> vos = hsmwOrderVehicleRelationService.getChildOrderDrivers(param);
            return new DataResponse(vos);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"查询订单的子订单信息，请联系管理员！");
        }
    }


    /**
     * 搜索关键词位置信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "项目经理端：搜索关键词位置信息 ", notes = "司机提交遇到的问题", produces = "application/json")
    @PostMapping("/searchKeywordsLocateInfo")
    public DataResponse submitProblem(@RequestParam  String  keyWords) {
        try {
            HashMap param = new HashMap();
            param.put("keywords",keyWords);
            List<GaodeSearchEntity> entities = gaoDeInfoUtils.searchKeywordsLocate(param);
            return new DataResponse(entities);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"获取订单详情失败，请联系管理员！");
        }
    }

    /**
     * 获取天气预报
     *
     * @param
     * @return
     */
    @ApiOperation(value = "获取天气预报", notes = "获取天气预报", produces = "application/json")
    @PostMapping("/getWeatherReport")
    public DataResponse getWeatherReport(@RequestBody WeatherVO vo) {
        try {
            if(StringUtils.isBlank(vo.getLng())){
                return  new DataResponse("您输入的经度为空，请重新输入！");
            }
            if(StringUtils.isBlank(vo.getLat())){
                return  new DataResponse("您输入的纬度为空，请重新输入！");
            }
            JSONObject result = GaoDeInfoUtils.getWeather(vo.getLng(),vo.getLat());
            //查询 方量统计
            return new DataResponse(result);
        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"获取天气预报，请联系管理员！");
        }
    }



    /**
     * 获取天气预报
     *
     * @param
     * @return
     */
    @ApiOperation(value = "获取24小时天气预报", notes = "获取24小时天气预报", produces = "application/json")
    @PostMapping("/getTetracosaWeatherReport")
    public DataResponse getTetracosaWeatherReport(@RequestBody WeatherVO vo) {
        try {
            if(StringUtils.isBlank(vo.getLng())){
                return  new DataResponse("您输入的经度为空，请重新输入！");
            }
            if(StringUtils.isBlank(vo.getLat())){
                return  new DataResponse("您输入的纬度为空，请重新输入！");
            }
            List<WeatherReportVO> list = new ArrayList();
            JSONObject result = GaoDeInfoUtils.getTetracosaWeather(vo.getLng(),vo.getLat());
            if(result != null){
                JSONArray hourly = result.getJSONArray("hourly");
                list = hourly.toJavaList(WeatherReportVO.class);

            }

            /*
            boolean is_insert = false;
            do{
                for (int i = 0; i < hourly.size(); i++) {
                    if(StringUtils.isNotBlank(vo.getOrderId())){
                        HsmwOrder hsmwOrder = hsmwOrderService.getById(vo.getOrderId());
                        LocalDateTime reachTime = hsmwOrder.getReachTime();



                        if(hour == strDate2){
                            is_insert = true;
                        }
                        if(is_insert && list.size() < 5){
                            list.add(hourly.get(i));
                        }
                    }
                }
            }while (list.size() != 5);*/
            return new DataResponse(list);

        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"获取天气预报，请联系管理员！");
        }
    }


    @ApiOperation(value = "获取天气预警", notes = "获取天气预警", produces = "application/json")
    @PostMapping("/getTetracosaWeatherLevel")
    public DataResponse getTetracosaWeatherLevel(@RequestBody WeatherVO vo){

        try {
            if(StringUtils.isBlank(vo.getLng())){
                return  new DataResponse("您输入的经度为空，请重新输入！");
            }
            if(StringUtils.isBlank(vo.getLat())){
                return  new DataResponse("您输入的纬度为空，请重新输入！");
            }
            JSONObject result = GaoDeInfoUtils.getTetracosaWeatherLevel(vo.getLng(),vo.getLat());

            return new DataResponse(result);

        }catch (Exception e){
            e.printStackTrace();
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"获取天气预报出错，请联系管理员！");
        }
    }



    public static void main(String[] args) {
        System.out.println(0==0.0);
    }



}
